package com.example.bigdata.scala.集合

/**
  *  Set 集合是一个不重复 、无序 集合 (默认 不可变)
  *  提供  查找最大值，最小元素 / 交叉补集 方法
  *  对于非Set集合（Array/ArrayBuffer/List/ListBuffer），在做交集、并集、差集时必须转换为Set，
  *  否则元素不去重没有意义。而对于非Set类型集合元素去重，也有个很好的方法：distinct
  */
object SetDemo {
  def main(args: Array[String]): Unit = {
    initTest()
    集合连接()
    最值()
    交差并集()
  }

  def initTest(): Unit = {
    val fruit = Set("apples", "oranges", "pears")
    val nums = Set[Int]()
    val nums1 : Set[Int] = Set(1,2,3)

    println("head of fruit " + fruit.head)
    println("tail of fruit " + fruit.tail)
    println("tails of fruit " + fruit.tails)
    println("Check if fruit is empty " + fruit.isEmpty)
    println("nums : " + nums.isEmpty)
    println("nums1 : " + nums1.isEmpty)
  }
  def 集合连接(): Unit = {
    val fruit1 = Set("apples", "oranges", "pears")
    val fruit2 = Set("mangoes", "banana")
    var fruit = fruit1 ++ fruit2
    println("fruit1 ++ fruit2\t" + fruit )

    // 添加元素
    fruit = fruit1.++(fruit2).+("xxx").+("x1","x1","x2")
    println("fruit1 ++ fruit2\t" + fruit)

  }
  def 最值(): Unit ={
    val num = Set(5,6,9,20,30,45)
    println("num.min : " + num.min)
    println("num.max : " + num.max)

    val num1 = Set(5,6,9,20,30,45)
    val num2 = Set(50,60,9,20,35,55)

    // find common elements between two sets
    println("num1.&(num2) : " + num1.&(num2))
    println("num1.intersect(num2) : " + num1.intersect(num2))

  }
  def 交差并集(): Unit ={
    val n1 = Set(5,6,9,20,30,45)
    val n2 = Set(50,60,9,20,35,55)

    val n3 = Set(2,3,"2")
    println("n3 : "+n3 )
    println("n1\t"+n1+"\nn2\t"+n2)

    //添加或删除元素，可以直接用+,-方法来操作，添加删除多个元素可以用元组来封装：
    println("n1 去掉 5，6，20\t" + (n1 - (5,6,20)))
    println("n1 添加 1，3，10\t" + (n1 + (1,3,10)))


    //交集
    println("\n交集1 : " + (n1 & n2))
    println("交集2 : " + (n1.intersect(n2)))
    println("交集3 : " + (n1 intersect n2)+"\n")

    //并集
    println("并集1 : " + (n1 ++ n2 ))
    println("并集2 : " + (n1 | n2 ))
    println("并集3 : " + (n1.union(n2)))
    println("并集4 : " + (n1 union n2)+"\n")

    //差集
    println("差集1 : " + (n1 -- n2))
    println("差集2 : " + (n1 &~ n2))
    println("差集3 : " + (n1 diff  n2))
    println("差集4 : " + (n1.diff(n2))+"\n")


  }
}
